using AutoMapper;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using ContentmanagementBase.Domain;
using ContentmanagementBaseWrite.API.Applications.Commands;
using MediatR;

namespace ContentmanagementBaseWrite.API.Applications.Commandhandlters
{
    /// <summary>
    /// 修改轮播图信息命令处理
    /// </summary>
    public class UpdateCarouselCommandHandler : IRequestHandler<UpdateCarouselCommand, ApiResult<bool>>
    {
        /// <summary>
        /// 轮播图仓储
        /// </summary>
        private readonly IBaseRepository<CarouelChartModel> _carouselRepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<UpdateCarouselCommandHandler> _logger;
        // <summary>
        /// 映射器
        /// </summary>
        private readonly IMapper mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="carouselRepository">轮播图仓储</param>
        /// <param name="logger">日志</param>
        public UpdateCarouselCommandHandler(
            IBaseRepository<CarouelChartModel> carouselRepository,
            ILogger<UpdateCarouselCommandHandler> logger,IMapper mapper)
        {
            _carouselRepository = carouselRepository;
            _logger = logger;
            this.mapper = mapper;
        }

        public async Task<ApiResult<bool>> Handle(UpdateCarouselCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证标题是否已存在
                var carouselDtos = _carouselRepository.GetAll().Where(x => x.CarouelChartTitle == request.CarouelChartTitle&&x.Id!=request.Id);
                // 如果已存在，返回错误
                if (carouselDtos.Any())
                {

                    return new ApiResult<bool>
                    {
                        code = ResultEnumCode.error,
                        message = "轮播图标题已存在!!!",
                        data = false,
                    };
                }

                // 验证输入参数
                if (request.Id <= 0)
                {
                    return new ApiResult<bool>
                    {
                        code = ResultEnumCode.fails,
                        message = "轮播图编号不能为空",
                        data = false
                    };
                }

                if (string.IsNullOrWhiteSpace(request.CarouelChartTitle))
                {
                    return new ApiResult<bool>
                    {
                        code = ResultEnumCode.fails,
                        message = "轮播图标题不能为空",
                        data = false
                    };
                }

                if (string.IsNullOrWhiteSpace(request.CarouelChartImages))
                {
                    return new ApiResult<bool>
                    {
                        code = ResultEnumCode.fails,
                        message = "轮播图图片不能为空",
                        data = false
                    };
                }

                // 查找要修改的轮播图
                var existingCarousel = mapper.Map<CarouelChartModel>(request);
                if (existingCarousel == null)
                {
                    return new ApiResult<bool>
                    {
                        code = ResultEnumCode.fails,
                        message = "轮播图不存在",
                        data = false
                    };

                }

                // 更新轮播图信息
                existingCarousel.CarouelChartTitle = request.CarouelChartTitle;
                existingCarousel.CarouelChartImages = request.CarouelChartImages;
                existingCarousel.ststus = request.ststus;
                existingCarousel.CarouelChartUrl = request.CarouelChartUrl;
                existingCarousel.Orderby = request.Orderby;
                existingCarousel.UpdatedTime = DateTime.Now;
               
                // 保存修改
                await _carouselRepository.UpdateAsync(existingCarousel);
             
                _logger.LogInformation("轮播图信息修改成功，ID：{Id}，标题：{Title}", 
                    request.Id, request.CarouelChartTitle);

                return new ApiResult<bool>
                {
                    code = ResultEnumCode.Ok,
                    message = "轮播图信息修改成功",
                    data = true
                };

            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "修改轮播图信息过程中发生异常，ID：{Id}", request.Id);

                return new ApiResult<bool>
                {
                    code = ResultEnumCode.fails,
                    message = $"修改轮播图信息失败：{ex.Message}",
                    data = false
                };
            }
        }
    }
} 